﻿// 在 http://fsharp.net 上了解有关 F# 的更多信息
// 请参阅“F# 教程”项目以获取更多帮助。
open System.Text.RegularExpressions
open System.Threading;
open System.Net;
open System.IO;
open System;

let getImageUrls htmlContent =
    let reg=new Regex(@"src=""(http://.+sinaimg.+?\.\w{3})""")
    let matches=reg.Matches(htmlContent)
    [for ma in matches do yield  ma.Groups.[1].Value ]


let getHtmlContent (url:string) =
    use wc=new WebClient()
    wc.DownloadString(url)

let downloadImg (imgUrls:list<string>,path) =
    use wc=new WebClient()
    let downloads=
        Async.Parallel[
            for url in imgUrls do
                let eName=url.Substring(url.LastIndexOf("."))
                let fileName=Path.Combine(path,url.Replace(@"/", "").Replace(":", "").Replace(eName, "").Replace(".", "") + eName)
                wc.DownloadFile(Uri url,fileName)
                printfn "%A" fileName
        ]
            |>Async.RunSynchronously

    0

[<EntryPoint>]
let main argv = 
    let url="http://jiandan.net/pic"
    let path =Path.Combine(Environment.CurrentDirectory,"download");
    let htmlContent=getHtmlContent url
    let imgUrls= getImageUrls htmlContent

    if (Directory.Exists(path)=false) then ignore( Directory.CreateDirectory(path))

    let down = downloadImg(imgUrls,path)



    0 // 返回整数退出代码

